package cn.hpclub.server.controller.admin;

import cn.hpclub.server.bean.SystemConfig;
import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.model.SysRole;
import cn.hpclub.server.service.SchoolSubjectService;
import cn.hpclub.server.util.*;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @FileName: BusinessAuthConfigController * @Author zhl
 * @Description:渠道类型与业务功能模组多级授权后台管理Controller
 * @Date 2016年6月27日 下午2:38:57
 * @CopyRight ZTE Corporation
 */
public class SchoolSubjectController extends BaseAdminController<SysRole>{
    private static final Logger logger = LoggerFactory.getLogger(SchoolSubjectController.class);

    public void list(){
        int defaultOrgId = initOrgTreeWithDefaultName();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("org_id") || "-1".equals(searchInfo.get("org_id"))){
            //searchInfo.put("org_id", defaultOrgId + "");
            searchInfo.put("org_id", "54835");//默认显示成都的数据
        }
        String startTime =  searchInfo.containsKey("start_time")
                ?searchInfo.get("start_time"): DateKit.getLastDay();
        String endTime = searchInfo.containsKey("start_time")
                ?searchInfo.get("start_time"): DateKit.getLastDay();
        searchInfo.put("start_time", startTime);
        searchInfo.put("end_time", endTime);
        setAttrs(searchInfo);
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        int pageSize = getParaToInt(PAGE_SIZE,10);
        Page page = SchoolSubjectService.service.getReportByPage(pageNumber,pageSize,searchInfo,Constant.Table.SCHOOL_SUBJECT_REPORT);
        setAttr(PAGER,page);
        render("/admin/school_subject_list.tpl");
    }




    /**
     * 导出到excel
     */
    public void exportAll(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("org_id") || "-1".equals(searchInfo.get("org_id"))){
            searchInfo.put("org_id", InterfaceUtil.getOrgId() + "");
        }
        String startTime =  searchInfo.containsKey("start_time")
                ?searchInfo.get("start_time")+" 00:00:00": DateKit.toStr(new Date()) + " 00:00:00";
        String endTime = searchInfo.containsKey("start_time")
                ?searchInfo.get("start_time")+" 23:59:59": DateKit.toStr(new Date()) + " 23:59:59";
        searchInfo.put("start_time", startTime);
        searchInfo.put("end_time", endTime);
        String name =generateFileName("校园专区业务办理日报统计");
        String filePath = getFilePath(name);
        JSONObject jo = null;
        String[] headers = new String[]{
                "地市","区县","网点编码","网点名称","网点类型","今日登录用户数","今日活跃用户数",
                "实名开卡办理量","携号登记",
                "有线宽带","区域流量","校园v网","校园前置营销","本地优惠"};
        String[] columns = new String[]{"CityName","AreaName","NumCode","DisplayName","class_name","loginCount","activeCount","newCard",
                "xiehao","yxkd","qyll","vNet","csbl","bdyh"};
        String sql = SchoolSubjectService.service.getReportBySXSSFSql(searchInfo,Constant.Table.SCHOOL_SUBJECT_REPORT);
        try{
            String exportFileUrl = ExcelLargeDataUtils.exportData(headers, columns,sql, name,filePath);
            jo = createDownloadSuccessJSONObject(exportFileUrl);
        }
        catch(Exception e){
            e.printStackTrace();
            jo = createDownloadErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

    private String getFilePath(String name){
        String filePath = JFinal.me().getServletContext().getRealPath(SystemConfig.UPLOAD_FILE_DIR + name);
        String fileDir = SystemConfigUtil.getSystemConfig().getUploadDir();
        logger.debug("cmccbusiness fileDir =" + fileDir);
        if(!StringUtils.isEmpty(fileDir)){
            filePath = fileDir + "/file/" + name;
        }
        return filePath;
    }
    private JSONObject createDownloadSuccessJSONObject(String exportFileUrl){
        JSONObject jo = new JSONObject();
        jo.put("status", 1);
        jo.put("message", "导出成功，点击下载");
        jo.put("url", exportFileUrl);
        renderJson(jo.toJSONString());
        return jo;
    }
    /**
     * @Title: createDownloadErrorJSONObject
     * @Description:TODO
     * @param e
     * @return JSONObject
     */

    private JSONObject createDownloadErrorJSONObject(Exception e){
        JSONObject jo = new JSONObject();
        jo.put("status", 0);
        jo.put("message", "导出失败：" + e.getMessage());
        return jo;
    }
    public void listForMonth(){
        int defaultOrgId = initOrgTreeWithDefaultName();
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("org_id") || "-1".equals(searchInfo.get("org_id"))){
            //searchInfo.put("org_id", defaultOrgId + "");
            searchInfo.put("org_id", "54835");//默认显示成都的数据
        }
        String startTime =  searchInfo.containsKey("start_time")
                ?searchInfo.get("start_time"): DateKit.toStr(new Date(),"yyyy-MM");

        searchInfo.put("start_time", startTime);

        setAttrs(searchInfo);
        int pageNumber = getParaToInt(PAGE_NUMBER, 1);
        int pageSize = getParaToInt(PAGE_SIZE,10);
        Page page = SchoolSubjectService.service.getReportByPage(pageNumber,pageSize,searchInfo, Constant.Table.SCHOOL_SUBJECT_REPORT_MONTH);
        setAttr(PAGER,page);
        render("/admin/school_subject_month_list.tpl");
    }
    private String generateFileName(String name){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HHmmssSSS");
        String curTime = sdf.format(date);
        String fileName = name + curTime + ".xlsx";
        return fileName;
    }
    /**
     * 导出到excel
     */
    public void exportAllForMonth(){
        ConcurrentHashMap<String, String> searchInfo = getSearchInfo();
        if(!searchInfo.containsKey("org_id") || "-1".equals(searchInfo.get("org_id"))){
            searchInfo.put("org_id", InterfaceUtil.getOrgId() + "");
        }
        /*String startTime =  searchInfo.containsKey("start_time")
                ?searchInfo.get("start_time")+" 00:00:00": DateKit.toStr(new Date()) + " 00:00:00";
        String endTime = searchInfo.containsKey("start_time")
                ?searchInfo.get("start_time")+" 23:59:59": DateKit.toStr(new Date()) + " 23:59:59";
        searchInfo.put("start_time", startTime);
        searchInfo.put("end_time", endTime);*/
        String name = generateFileName("校园专区业务办理月报统计");
        String filePath = getFilePath(name);
        JSONObject jo = null;
        String[] headers = new String[]{
                "地市","区县","网点编码","网点名称","网点类型","本月登录用户数","本月活跃用户数",
                "实名开卡办理量","携号登记",
                "有线宽带","区域流量","校园v网","校园前置营销","本地优惠"};
        String[] columns = new String[]{"CityName","AreaName","NumCode","DisplayName","class_name","loginCount","activeCount","newCard",
                "xiehao","yxkd","qyll","vNet","csbl","bdyh"};
        String sql = SchoolSubjectService.service.getReportBySXSSFSqlForMonth(searchInfo,Constant.Table.SCHOOL_SUBJECT_REPORT_MONTH);
        try{
            String exportFileUrl = ExcelLargeDataUtils.exportData(headers, columns,sql, name,filePath);
            jo = createDownloadSuccessJSONObject(exportFileUrl);
        }
        catch(Exception e){
            e.printStackTrace();
            jo = createDownloadErrorJSONObject(e);
        }
        renderJson(jo.toJSONString());
    }

}
